package io.gitee.yth.design.pattern.test.core.pattern.behavioral.memento;

import java.util.Optional;

/**
 * @author yth
 * @since 2023-05-01-18:22
 */
public class Position {

    private static final Caretaker caretaker = Caretaker.getInstance();

    private int x;
    private int y;

    public Position(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "Position{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }

    public void move(int x_off, int y_off) {
        caretaker.save(this.getClass(), createMemento());
        x += x_off;
        y += y_off;
    }

    public boolean undo() {
        final Optional<Memento> memento = caretaker.popLatest(this.getClass());
        memento.map(e -> (PositionMemento) e)
                .ifPresent(this::setMemento);
        return memento.isPresent();
    }

    private PositionMemento createMemento() {
        return new PositionMemento(x, y);
    }

    private void setMemento(PositionMemento memento) {
        this.x = memento.getX();
        this.y = memento.getY();
    }

}
